<template>
  <div>
    <MyDialog
      v-if="visible"
      v-model="listVisible"
      title="用户列表"
      @confirm="handleConfirm"
      @cancel="handleConfirm"
    >
      <div class="dialog_body">
        <div style="height: 30px;">
        <button style="float: right;" @click="addUser">添加</button></div>
        <div class="border_list">
        <div v-for="(item, index) in userList" class="list_box" :key="index">
            <img class="list_img" :src="item.url" />
         <span>用户名：</span> <span 
         :title="item.user_name"
         class="name_span">{{ item.user_name }}</span>
      
<span style="position: absolute;right: 45px;">
          <button @click="editUser(item)">修改</button>
          <button @click="deleteUser(item)">删除</button>
        </span>
        </div>
    </div>
      </div>
      <!-- <template #footer>

   
      </template> -->
    </MyDialog>

    <MyDialog
      v-if="addVisible"
      v-model="addVisible"
      title="单用户操作"
      @confirm="addConfirm"
      @cancel="addCancel"
    >
      <div class="add_body">
   
       <div>用户名：<input class="name_input" v-model="currentUser.user_name" /></div> 
       <div style="margin-top: 30px;">
        用户头像： <img class="add_img" :src="currentUser.url" />
        <input
     
          ref="fileInput"
          type="file"
          accept="image/*"
          @change="handleFileChange"
          style="display: none"
        />
        <button @click="triggerFileInput">选择图片</button>
       </div> 
      </div>
      <!-- <template #footer>

   
      </template> -->
    </MyDialog>
  </div>
</template>

<script setup>
import MyDialog from "@/components/Dialog.vue";
import { onMounted, computed, ref } from "vue";
import { convertToBase64, copyObject } from "@/tool/tool.js";
import { invoke } from "@tauri-apps/api/core";
const props = defineProps({
  visible: {
    type: Boolean,
    default: false,
  },
  userList: {
    type: Array,
    default: [],
  },
  basePath: {
    type: String,
    default: "",
  },
});
const addVisible = ref(false);
const listVisible = computed({
  get() {
    return props.visible;
  },
  set(newVal) {
    emit("update:visible", newVal);
  },
});
const fileInput = ref(null);
const userConfig = {
  imgtype: ".jpeg",
  mes_type: "image",
  user_name: "",
  name: "",
  url: "",
  user_id: "",
};
const currentUser = ref({});
const emit = defineEmits(["update:visible"]);
onMounted(() => {

});
function handleConfirm(params) {
  emit("update:visible", false);

}
function copy(params) {
  return JSON.parse(JSON.stringify(params));
}
function addUser() {
  currentUser.value = {};

  addVisible.value = true;
}
function deleteUser(row) {
  let data = copyObject(row);
  delete data.url


  invoke("deleteUser", {
    path: props.basePath,
    jsonData: JSON.stringify(data),
  }).then((res) => {
    console.log(res);
    if (res === "OK") {

    } else {
    }
  });
}
function editUser(row) {
  currentUser.value = row;
  addVisible.value = true;
}
const triggerFileInput = () => {
  fileInput.value.click();
};
const handleFileChange = async (e) => {
  const file = e.target.files[0];
  if (!file) return;

  // 验证是否为图片类型
  if (!file.type.startsWith("image/")) {
    alert("请选择图片文件！");
    return;
  }
  let base64Str = await convertToBase64(file);

  const [prefix, data] = base64Str.split(",");
  // let obj = {
  //   time:new Date(),
  //   mes_type:'image',
  //   imgtype: 'jpeg',
  //   base64_header:prefix,
  //   url: data,
  //   user_id:currentUser.value.user_id,
  //   name: currentUser.value.name,
  // }
  currentUser.value.url = base64Str;
  // currentUser.value.url = URL.createObjectURL(file)

  // 存储文件信息
  //   fileInfo.value = {
  //     name: file.name,
  //     type: file.type,
  //     size: file.size,
  //     lastModified: file.lastModified
  //   }

  //   // 生成预览图
  //   previewUrl.value = URL.createObjectURL(file)
};

async function addConfirm() {
  if (!currentUser.value.user_name || !currentUser.value.url) {
    alert("填写完整");
  }

  let data = {};

  let type = currentUser.value.user_id===undefined?"addUser":"editUser"
  if (type == "editUser") {
   data = copyObject(currentUser.value)
  } else if (type == "addUser") {
    data = copyObject(userConfig)
    let uid = `userId_${new Date().getTime()}_name`;
    data.user_id = uid;
    data.name = uid;
    data.user_name = currentUser.value.user_name;
  }
  try {
    
  } catch (error) {
    
  }
  const [prefix, urlData] = currentUser.value.url.split(",");
  
  if(urlData){
    data.base64_header = prefix;
  data.url = urlData;
  }else{

  }



  invoke(type, {
    path: props.basePath,
    jsonData: JSON.stringify(data),
  }).then((res) => {
  
    if (res === "OK") {
  
    } else {
    }
  });
}
function addCancel(params) {
  addVisible.value = false;
  currentUser.value;
}
</script>

<style scoped>
.list_img {
  width: 20px;
  height: 20px;
  vertical-align: middle;
}
.add_img{
    width: 60px;
  height: 60px;
  vertical-align: middle;margin-right: 40px; 
}
.name_input {
  width: 200px;
  display: inline-block;
  height: 50px;
}
.dialog_body{
    width: 100%;
    min-height: 350px;
    overflow: auto;
    position: relative;
}
.list_box{
display: flex;
align-items: center;
position: relative;
border-bottom: solid 1px rgb(201, 199, 199);
padding-bottom: 5px;
padding-top: 5px;
}
button{
    font-size: 14px;
    padding: 2px
}
.border_list{
    border: solid 1px black;
    min-height: 320px;
    padding: 10px;

    width: 90%;
}
.add_body{
    min-height: 150px;
    vertical-align: middle;
    width: 450px;
}
input{
    height: 20px!important;

}
.name_span{
    width: 70px;
    white-space: nowrap;
    
}
</style>